package org.comet.auxiliary.client.swing.versions.v1;

import cn.liaobei.EasyLogin;
import cn.liaobei.bean.UserInfo;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.SneakyThrows;
import org.apache.http.ParseException;
import org.apache.http.client.utils.DateUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.comet.auxiliary.client.liaobei.sql.ResultSetExtractor;
import org.comet.auxiliary.client.liaobei.sql.SqliteHelper;
import org.comet.auxiliary.client.liaobei.util.AuPaly;
import org.comet.auxiliary.client.liaobei.util.RequestUtil;
import org.comet.auxiliary.client.liaobei.util.SystemModel;
import org.comet.auxiliary.client.liaobei.wss.MsgHelper;
import org.comet.auxiliary.client.swing.BodyFrame;
import org.comet.auxiliary.client.swing.FriendListFrame;
import org.comet.auxiliary.client.swing.OperationCellEditor;
import org.comet.auxiliary.client.swing.TableFrame;
import org.comet.auxiliary.common.handler.soft.SoftHandler;
import org.comet.auxiliary.common.swing.AbstractSettingSwing;
import org.comet.auxiliary.common.swing.SettingSwing;
import org.comet.auxiliary.common.swing.SwingHelper;
import org.comet.auxiliary.common.util.*;
import org.comet.auxiliary.common.util.config.ClientConfigHelper;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @author wq
 * @date 2019/10/8
 * @description setting
 */
public class SettingFrame extends AbstractSettingSwing implements ActionListener, SettingSwing {

    private JTable recordGrid;
    private JButton startBtn;
    private JButton stopBtn;
    private JTextArea logTextArea;
    private JScrollPane logScrollPane;
    private JTextField ridText;
    private JTextField uidText;
    private JTextField takeSleepText;
    private JTextField firstSomeText;
    private JTextField lastSomeText;
    private JCheckBox ridCbx;
    private JCheckBox uidCbx;
    private JCheckBox firstSomeCbx;
    private JCheckBox lastSomeCbx;
    private Color commonBgColor = new Color(252, 244, 228);
    private ConcurrentHashMap<String, MapBean> accountMap = new ConcurrentHashMap<>(16);
    private ConcurrentHashMap<String, SoftHandler> softHandlerMap = new ConcurrentHashMap<>(16);
    private String work = "0";
    private volatile String fullSoftHandlerPhone = null;
    public static UserInfo userInfo=null;
    public static List<Map<String,Object>> buddyList = new ArrayList<>();
    public static List<Map<String,Object>> groupList = new ArrayList<>();
    public static String fbLoop = null;
    public static String fbId = null;
    public static  String fbName=null;
    public static  JTextArea znfbLogText  =  new JTextArea("运行日志：", 18, 31);;

    private static JTextField fbjeText;
    private static JTextField bsText;
    public static JTextField hbbtText;
    private static JTextField jgText;
    private static JTextField zfmmText;
    private static JScrollPane znfbLogScrollPane;
    public static  JButton ksBtn;
    private static JButton saveBtn;
    private static JCheckBox f ;
    private static JTextField tz ;
    public static  Integer num = 1;
    public static List<String> titleList = new ArrayList<>();
   public static  JTable zlLogText  = new JTable();
   public static  JTextField blText;
    public static  JCheckBox znhm;
    //是否继续发包
    public static Boolean isSend=true;
  public static   JCheckBox zltzfb ;

   public  JCheckBox lbjx;
    public JCheckBox cctzfb;
    public static   JCheckBox k;
    public static JTextField hm;
    public static JCheckBox lqslhb;
    public static JTextField m;
    public static SqliteHelper sqliteHelper;
    public static JLabel fblsText;
    public static  JLabel fbbssText;
    public static  JLabel lqjeText;
    public static JLabel ykText;
    public static  boolean isSendOne = false;


    //发包托
  public static  JTextArea fbLogText = new JTextArea("运行日志：", 14, 48);
  public  JTextField fbjeText1;
    public JTextField  fbbsText1;
    public  JTextField fbjgText1;
    public  JTextField zdtzbsText;
    public  JTextField zdtzjeText;
    public  JButton fbkgBtn;
    public static  Integer fbnum = 1;
    public static Double fbMoney = 0d;


    //中雷提示框表格数据
    public static List<Map<String,Object>> tableDate = new ArrayList<>();
    static DefaultTableModel model;
    private static JScrollPane scrollPane;



    public static JButton isPf;


    public static void main(String[] args) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        sqliteHelper = new SqliteHelper("red.db");
        UUID uuid= UUID.randomUUID();
        try {
            Map<String,Object> map=      EasyLogin.login(uuid.toString(),new MsgHelper());
            System.out.println(map.toString());
            userInfo = new UserInfo();
            userInfo.setUuid(uuid.toString());
            userInfo.setUid(map.get("uid").toString());
            userInfo.setTk(map.get("tk").toString());
            userInfo.setRtk(map.get("rtk").toString());
            userInfo.setUnk(map.get("unk").toString());
            Map<String ,Object> map1 = RequestUtil.queryFriendList(userInfo.getUuid(),userInfo.getUid(),userInfo.getTk());
            System.out.println(map1);
            Map<String,Object> group1 = (Map<String, Object>) map1.get("rl");
            Map<String,Object> group2 = (Map<String, Object>) map1.get("ul");
            groupList = (List<Map<String,Object>>)group1.get("l");
            buddyList = (List<Map<String,Object>>)group2.get("l");
        } catch (Exception e) {
            e.printStackTrace();
        }

        ClientConfigHelper.setConfigPrefix("lapu.seconds.");
        ClientConfigHelper.debug();
        SwingHelper.setCustomFont(new Font("宋体", Font.PLAIN, 13));
        SettingFrame settingFrame = new SettingFrame();
        settingFrame.openSetting(null);
        settingFrame.setResizable(true);
        //初始化数据库

//
//        MapBean config = ClientConfigHelper.getConfig();
//        System.out.println(config.get("lapu.seconds.rid"));
//        System.out.println(config);
//        Object otherConfig = ClientConfigHelper.getOtherConfig("lapu.seconds.rid");
//        System.out.println(otherConfig);
    }

    public static void refreshTopData() {
       List<Map<String,Object>> list= getList("userdata");
        Map<String,Object> map=list.get(0);
        fblsText.setText(map.get("fbls").toString());
        lqjeText.setText(map.get("lq_money").toString());
        fbbssText.setText(map.get("send_page_num").toString());
        ykText.setText(map.get("yk").toString());
    }

    @Override
    public void addLog(String log) {
        if (znfbLogText == null) {
            return;
        }
        znfbLogText.append("\r\n" + log);
        int maximum = znfbLogScrollPane.getVerticalScrollBar().getMaximum();
        znfbLogScrollPane.getViewport().setViewPosition(new Point(0, maximum));
    }


//    @SneakyThrows
    @Override
    public void actionPerformed(ActionEvent e) {
        String actionCommand = e.getActionCommand();
        if ("sendGroup".equals(actionCommand)) {
            FriendListFrame listFrame = new FriendListFrame(this, title, 453, 315);
            listFrame.openFriendList(buddyList,groupList);
            String idObj = listFrame.getIdObj();
            String idType = listFrame.getIdType();
            String idName=  listFrame.getIdName();
            if (!StringUtil.isEmpty(idObj)) {
                fbLoop = idType;
                fbId = idObj;
                fbName= idName;
                System.out.println(idName);
                znfbLogText.append("\r\n当发包方式:"+idType+",发包id:"+idObj);
                znfbLogText.append("\r\n当前用户为:"+userInfo.getUnk());
                SettingFrame.znfbLogText.setCaretPosition(SettingFrame.znfbLogText.getText().length());
            }
            listFrame.dispose();
            listFrame = null;
        } else if ("sendOne".equals(actionCommand)) {
            isSendOne = true;
            sendPack(getTitle1());
        }else if("begin".equals(actionCommand)){
            isSendOne = false;
          begin();
        }else if("setTitle".equals(actionCommand)){
            titleList.clear();
            BodyFrame listFrame = new BodyFrame(this, title, 100, 400);
            List<Map<String,Object>> titles = this.getList("title");
            if(!Objects.isNull(titles)){
                for (Map<String, Object> stringObjectMap : titles) {
                    titleList.add(StringUtil.isBlank(stringObjectMap.get("name").toString())?" ":stringObjectMap.get("name").toString());
                }
            }
            listFrame.openFriendList(this.titleList);
            this.titleList = listFrame.titleList;
            System.out.println(listFrame.titleList.toString());
            saveTitle();
        }else if("saveConfig".equals(actionCommand)){
            save();
        }else if("ctjBtn".equals(actionCommand)){
            //查询红包数据
            List<Map<String,Object>>  list =  getList("reddata");
            TableFrame tableFrame = new TableFrame(this,title,600,400);
            tableFrame.openFriendList(list);
        }else if("fbbegin".equals(actionCommand)){
            //发包托开始
            ThreadFactory threadFactory = (new ThreadFactoryBuilder()).setNameFormat("take-packet-schedule-%d1").build();
            ScheduledExecutorService takePacketPool = new ScheduledThreadPoolExecutor(Integer.MAX_VALUE, threadFactory, new ThreadPoolExecutor.AbortPolicy());
            String text = fbkgBtn.getText();
            if(text.equals("开始")){
                System.out.println(fbjgText1.getText());
                fbkgBtn.setText("暂停");
                //开启定时任务
                takePacketPool.scheduleWithFixedDelay(() -> {
                    boolean issend = true;
                    System.out.println("开始发包");

                    System.out.println(fbnum);
                    System.out.println(fbMoney);
                    if(fbnum>=Integer.parseInt(zdtzbsText.getText()) || fbMoney>=Double.parseDouble(zdtzjeText.getText())){
                        issend = false;
                        System.out.println("暂停1");
                        takePacketPool.shutdown();
                        fbkgBtn.setText("开始");
                        fbnum=1;
                        fbMoney=0d;
                        System.out.println("发包结束");
                    }
                    if(fbkgBtn.getText().equals("开始")){
                        System.out.println("暂停2");
                        System.out.println("停止发包");
                        issend = false;
                        takePacketPool.shutdown();
                    }
                    if(issend){
                        Double money =Double.parseDouble(zdtzjeText.getText())- fbMoney;
                        if(money<Double.parseDouble(fbjeText1.getText())){
                                sendPack1(getTitle1(),new Double(money).intValue());
                                fbMoney=fbMoney+new Double(money).intValue();
                        }else{
                            sendPack1(getTitle1());

                            fbMoney=fbMoney+Double.parseDouble(fbjeText1.getText());
                        }
                        fbnum++;

                    }

                },1 ,Integer.parseInt(fbjgText1.getText()) , TimeUnit.SECONDS);
            }else{
                System.out.println(2);
                fbkgBtn.setText("开始");

            }




        }else if("xzfbdx".equals(actionCommand)){
            FriendListFrame listFrame = new FriendListFrame(this, title, 453, 315);
            listFrame.openFriendList(buddyList,groupList);
            String idObj = listFrame.getIdObj();
            String idType = listFrame.getIdType();
            if (!StringUtil.isEmpty(idObj)) {
                fbLoop = idType;
                fbId = idObj;
                znfbLogText.append("\r\n发包方式:"+idType+",发包id:"+idObj);
                SwingHelper.addLog("CHOSE_SEND_OBJ_SUCCESS", idType, idObj);
            }
            listFrame.dispose();
            listFrame = null;
        }else if("isPf".equals(actionCommand)){
            if(isPf.getText().equals("开始")){
                isPf.setText("关闭");
            }else{
                isPf.setText("开始");
            }
        }
    }

   public static ThreadFactory threadFactory = (new ThreadFactoryBuilder()).setNameFormat("take-packet-schedule-%d").build();
    static Date sendTime=null;
    public static void begin() {
      Integer jgNum=  Integer.parseInt(getJgText());
        ScheduledExecutorService  takePacketPool = new ScheduledThreadPoolExecutor(Integer.MAX_VALUE, threadFactory, new ThreadPoolExecutor.AbortPolicy());
        String text = ksBtn.getText();
        if(text.equals("开始")){

            // 每次点击开始,清空赔付金额和领取 金额(日志中)
            MsgHelper.xpfMoney = 0d;
            MsgHelper.zlqMoney = 0d;


            ksBtn.setText("暂停");
            System.out.println(takePacketPool.isTerminated());

            //开启定时任务
            takePacketPool.scheduleWithFixedDelay(() -> {

                boolean issend=true;
                System.out.println("开始发包"+f.isSelected());
                if(  !isSend){
                    ksBtn.setText("开始");
                    isSend = true;
                    znfbLogText.append("\r\n发包结束");
                    SettingFrame.znfbLogText.setCaretPosition(SettingFrame.znfbLogText.getText().length());
                    issend = false;
                    takePacketPool.shutdown();
                }
                if(f.isSelected()){
                    System.out.println(num);
                    if(num>=Integer.parseInt(tz.getText())+1){
                        ksBtn.setText("开始");
                        num=1;
                        isSend = true;
                        znfbLogText.append("\r\n发包结束");
                        SettingFrame.znfbLogText.setCaretPosition(SettingFrame.znfbLogText.getText().length());
                        System.out.println("发包结束");
                        issend = false;
                        takePacketPool.shutdown();
                    }
                }
                if(ksBtn.getText().equals("开始")){
                    issend = false;
                    System.out.println("停止发包");
                    takePacketPool.shutdown();
                }
                if(issend){
                    if(sendTime!=null){
                        long  num = (new Date().getTime()-sendTime.getTime())/1000;
                        if(num<jgNum){
                            int num11 = jgNum-(int)num;
                            try {
                                znfbLogText.append("发包过快,休眠"+num11+"秒");
                                Thread.sleep(num11);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    znfbLogText.append("\r\n"+DateUtils.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss")+"发送第"+num+"包");
                    SettingFrame.znfbLogText.setCaretPosition(SettingFrame.znfbLogText.getText().length());
                    String loop=sendPack(getTitle1());
                    //记录当前发包时间
                    sendTime=new Date();
                    if(loop.equals("error")){
                        znfbLogText.append("\r\n发包出错，停止发包");
                        SettingFrame.znfbLogText.setCaretPosition(SettingFrame.znfbLogText.getText().length());
                        num=1;
                        ksBtn.setText("开始");
                        AuPaly auPaly =new AuPaly("./error.au");
                        auPaly.play();
                        takePacketPool.shutdown();
                    }
                    num++;
                }
                SettingFrame.znfbLogText.setCaretPosition(SettingFrame.znfbLogText.getText().length());

            },1 ,jgNum , TimeUnit.SECONDS);
        }else{
            System.out.println("停止");
            ksBtn.setText("开始");
            takePacketPool.shutdown();
            System.out.println(takePacketPool.isTerminated());
        }
    }

    private void saveTitle() {
        try {
            sqliteHelper.executeUpdate("delete from title where userid="+SettingFrame.userInfo.getUid());
            for (String s : this.titleList) {
                    sqliteHelper.executeUpdate("insert into title values('"+s+"','"+SettingFrame.userInfo.getUid()+"')");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取标题
    public static   String getTitle1(){
        String title = null;
        System.out.println(titleList.toString());
        if(znhm.isSelected()){
            //在所有标题中选中一个发送
            String titles = titleList.get((int) (Math.random() * titleList.size()) );
            String[] titleAry=titles.split("/");
            title = titleAry[(int) (Math.random() * titleAry.length)];
        }else{
            String[] titleAry=hbbtText.getText().split("/");
            title = titleAry[(int) (Math.random() * titleAry.length)];
        }
        return title;
    }

    //获取标题
    public static String getTitle2(){
        String title = null;
        System.out.println(titleList.toString());
        //在所有标题中选中一个发送
        String titles = titleList.get((int) (Math.random() * titleList.size()) );
        String[] titleAry=titles.split("/");
        title = titleAry[(int) (Math.random() * titleAry.length)];

        return title;
    }



    public void sendPack1(String title,Integer money){
        System.out.println(title);
        String data = null;
        //判断是否是群聊发包
        if(fbLoop.equals("群聊发包")){
            try {
                Integer  pagenum =new  Double(fbbsText1.getText()).intValue();
                System.out.println("发包报数"+pagenum);
                String str=       data= RequestUtil.sendRelationPacket(title,money*100,Integer.parseInt(fbbsText1.getText()),fbId,zfmmText.getText(),userInfo.getTk(),userInfo.getUid(),userInfo.getUuid());
                System.out.println(str);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                data=  RequestUtil.sendPacket(title,money*100,fbId,zfmmText.getText(),userInfo.getTk(),userInfo.getUid(),userInfo.getUuid());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Map <String,Object> result= JsonUtils.getMap(data);
        System.out.println(result);
        if(Objects.equals(result.get("r"),"0")){
            fbLogText.append("\r\n发包成功,    发送金额:"+money);

//               SwingHelper.addLog("SEND_PAG_SUCCESS",userInfo.getUnk());
        }else{
               Map<String,Object> dataJson = (Map<String, Object>)  result.get("data");

                znfbLogText.append("\r\n发包失败,原因："+dataJson.get("srmsg").toString());
            fbLogText.append("\r\n发包失败");
        }
        SettingFrame.fbLogText.setCaretPosition(SettingFrame.fbLogText.getText().length());
    }





    public void sendPack1(String title){
        System.out.println(title);
        String data = null;
        //判断是否是群聊发包
        if(fbLoop.equals("群聊发包")){
            try {
                Integer  pagenum =new  Double(fbbsText1.getText()).intValue();
                System.out.println("发包报数"+pagenum);
                String str=       data= RequestUtil.sendRelationPacket(title,Integer.parseInt(fbjeText1.getText())*100,Integer.parseInt(fbbsText1.getText()),fbId,zfmmText.getText(),userInfo.getTk(),userInfo.getUid(),userInfo.getUuid());
                System.out.println(str);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                data=  RequestUtil.sendPacket(title,Integer.parseInt(fbjeText1.getText())*100,fbId,zfmmText.getText(),userInfo.getTk(),userInfo.getUid(),userInfo.getUuid());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Map <String,Object> result= JsonUtils.getMap(data);
        System.out.println(result);
        if(Objects.equals(result.get("r"),"0")){
            fbLogText.append("\r\n发包成功,    发送金额:"+Integer.parseInt(fbjeText1.getText()));
//               SwingHelper.addLog("SEND_PAG_SUCCESS",userInfo.getUnk());
        }else{
            Map<String,Object> dataJson = (Map<String, Object>)  result.get("data");
//                SwingHelper.addLog("SEND_PAG_ERROR",userInfo.getUnk(),dataJson.get("srmsg"));
            znfbLogText.append("\r\n发包失败,原因："+dataJson.get("srmsg").toString());
            fbLogText.append("\r\n发包失败");
        }
    }

    public static String getFbjeText(){
        String text= fbjeText.getText();
        if(text.contains("/")){
         String[] je =    text.split("/");
         text = je[new Random().nextInt(je.length)];
         return text;
        }else{
            return text;
        }
    }



    public static String getJgText(){
        String text= jgText.getText();
        if(text.contains("/")){
            String[] je =    text.split("/");
            text = je[new Random().nextInt(je.length)];
            return text;
        }else{
            return text;
        }
    }


    public static String sendPack(String title){
        System.out.println(title);
        String data = null;
        String fbje = getFbjeText();
        //判断是否是群聊发包
        if(fbLoop.equals("群聊发包")){
            try {
                System.out.println("群聊发包");
               String str=       data= RequestUtil.sendRelationPacket(title,Integer.parseInt(fbje)*100,Integer.parseInt(bsText.getText()),fbId,zfmmText.getText(),userInfo.getTk(),userInfo.getUid(),userInfo.getUuid());
                System.out.println(str);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                data=  RequestUtil.sendPacket(title,Integer.parseInt(fbje)*100,fbId,zfmmText.getText(),userInfo.getTk(),userInfo.getUid(),userInfo.getUuid());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Map <String,Object> result= JsonUtils.getMap(data);
        System.out.println(result);
        if(Objects.equals(result.get("r"),"0")){
            znfbLogText.append("\r\n发包成功");
            //插入数据到reddata表中
            try {
                  sqliteHelper.executeQuery("select * from reddata where userid = " + userInfo.getUid()+" and groupno = "+fbId, new ResultSetExtractor<Object>() {
                    @Override
                    public List<Map<String, Object>> extractData(ResultSet rs) {
                        try {
                            if(!rs.next()){
                                String sql = "insert into reddata values('"+userInfo.getUid()
                                        +"','"+new String(userInfo.getUnk().getBytes("utf-8"),"utf-8")
                                        +"','"+new String(fbName.getBytes("utf-8"),"utf-8")
                                        +"','"+fbId
                                        +"','"+1
                                        +"','"+Integer.parseInt(fbje)
                                        +"','"+(0)
                                        +"','"+userInfo.getUid()
                                        +"','"+0
                                        +"')";
                                System.out.println(sql);
                                sqliteHelper.executeUpdate(sql);
                            }else{
                               String sql="update reddata set " +
                                        "phone="+userInfo.getUid()+
                                        ",name='"+new String(userInfo.getUnk().getBytes("utf-8"),"utf-8")+
                                        "',groupname = '"+new String(fbName.getBytes("utf-8"),"utf-8")+
                                        "' , groupno = "+fbId+
                                        ",sendnum = sendnum+1,sendmoney=sendmoney+"+Integer.parseInt(fbje)+" where userid="+userInfo.getUid()+" and groupno = "+fbId;
                                System.out.println(sql);
                                sqliteHelper.executeUpdate(sql);
                                sqliteHelper.executeUpdate("update reddata set yk = lqmoney -sendmoney   where userid="+userInfo.getUid()+" and groupno = "+fbId);
                            }
                        } catch (SQLException | ClassNotFoundException throwables) {
                            throwables.printStackTrace();
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                });



                return "success";
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }


//               SwingHelper.addLog("SEND_PAG_SUCCESS",userInfo.getUnk());
        }else{

            AuPaly auPaly =new AuPaly("./error.au");
            auPaly.play();
               Map<String,Object> dataJson = (Map<String, Object>)  result.get("data");
               znfbLogText.append("\r\n发包失败,原因："+dataJson.get("srmsg").toString());
               SettingFrame.znfbLogText.setCaretPosition(SettingFrame.znfbLogText.getText().length());
            return "error";
        }
        return null;
    }



    private void batchLogout() {
        for (String phone : accountMap.keySet()) {
            logoutByPhone(phone);
        }
        renderTableByAccount();
    }

    private void batchLogin() throws Exception {
        for (String phone : accountMap.keySet()) {
            loginByPhone(phone);
        }
        renderTableByAccount();
    }

    private void batchChangeEnable(boolean enable) {
        ridText.setEnabled(enable);
        uidText.setEnabled(enable);
        ridCbx.setEnabled(enable);
        uidCbx.setEnabled(enable);
        takeSleepText.setEnabled(enable);
        firstSomeCbx.setEnabled(enable);
        lastSomeCbx.setEnabled(enable);
        lastSomeText.setEnabled(enable);
        firstSomeText.setEnabled(enable);
    }

    private void renderByDrop(String loginText) {
        String[] accountArray = loginText.split("\n");
        for (String acc : accountArray) {
            if (StringUtil.isBlank(acc)) {
                continue;
            }
            String[] accArr = acc.split("----");
            if (accArr.length < 2) {
                addLog("格式错误: " + acc);
                continue;
            }
            String phone = accArr[0].trim();
            String pwd = accArr[1].trim();
            if (accountMap.containsKey(phone)) {
                addLog("账号已存在: " + phone);
                continue;
            }
            MapBean record = new MapBean();
            record.put("id", "");
            record.put("nick", "");
            record.put("pwd", pwd);
            record.put("phone", phone);
            record.put("bal", "0");
            record.put("status", "离线");
            accountMap.put(phone, record);
        }
        renderTableByAccount();
    }

    private synchronized void renderTableByAccount() {
        try {
            ArrayList<MapBean> list = new ArrayList<>(accountMap.values());
            renderTable(list);
        } catch (Exception e) {
            System.err.println("== render has error :: " + e.getMessage());
        }
    }

    private void logoutByPhone(String phone) {
        SoftHandler softHandler = softHandlerMap.remove(phone);
        if (softHandler != null) {
            try {
                softHandler.disconnect();
                softHandler.destroy();
                MapBean accountInfo = accountMap.get(phone);
                if (accountInfo != null) {
                    accountInfo.put("status", "离线");
                }
                if (phone.equals(fullSoftHandlerPhone)) {
                    fullSoftHandlerPhone = null;
                    SwingHelper.addLog("IMPORT_LOGOUT_TIP", phone);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void loginByPhone(String phone) throws Exception {
      /*  MapBean accountInfo = accountMap.get(phone);
        if (accountInfo != null) {
            String pwd = accountInfo.getString("pwd");
            String status = accountInfo.getString("status");
            if ("在线".equals(status)) {
                return;
            }
            SoftHandler lapu = softHandlerMap.get(phone);
            boolean firstInit = lapu == null;
            if (firstInit) {
                lapu = new LapuSoftHandler();
                lapu.init(UUIDUtils.newID());
                softHandlerMap.put(phone, lapu);
            }
            SoftHandler finalLapu = lapu;
            boolean onlyLogin = false;
            if (!StringUtil.isBlank(fullSoftHandlerPhone)) {
                onlyLogin = true;
            }
            boolean finalOnlyLogin = onlyLogin;
            lapu.loginByAccount(phone, pwd, onlyLogin, () -> {
                if (!finalOnlyLogin) {
                    fullSoftHandlerPhone = phone;
                    SwingHelper.addLog("IMPORT_LOGIN_TIP", phone);
                }
                Object loginUser = finalLapu.getLoginUser();
                if (loginUser instanceof UserInfo) {
                    UserInfo userInfo = (UserInfo) loginUser;
                    accountInfo.put("id", userInfo.getUid());
                    accountInfo.put("nick", userInfo.getUnk());
                    accountInfo.put("bal", userInfo.getBal());
                    accountInfo.put("status", "在线");
                    SwingHelper.addLog("LOGIN_SUCCESS_TIP", phone, pwd);
                }
            }, () -> {
                //error
                accountInfo.put("status", "登录失败");
                SwingHelper.addLog("LOGIN_FAIL_TIP", phone, pwd);
            });
            //第一次登陆的号进入此方法，代表一共登陆多少个用户，只有进入此方法的用户才可以领取红包
            if (firstInit) {
                SoftHandler finalLapu1 = lapu;
                ThreadUtil.executeByCommon(()->{
                    System.out.println("ThreadId："+Thread.currentThread().getId()+"ThreadName："+getName());
                    FunctionHandler packetFunctionHandler = new PalmFunctionHandler(finalLapu1);
                    finalLapu1.setFunctionHandler(packetFunctionHandler);
                    packetFunctionHandler.addCallback("sendLast", (data)->{
                    });
                });
            }

        }*/
    }

    private void choseObj(boolean choseRid) throws Exception {
//        FriendListFrame listFrame = new FriendListFrame(this, title, 353, 315);
//        Map<String, UserInfo> friendInfo = new HashMap<>();
//        Map<String, RelationInfo> relationInfo = new HashMap<>();
//        SoftHandler firstSoftHandler = getFirstSoftHandler();
//        if (firstSoftHandler == null) {
//            JOptionPane.showMessageDialog(this, "请先登录", title, JOptionPane.ERROR_MESSAGE);
//            return;
//        }
//        if (choseRid) {
//            relationInfo = firstSoftHandler.getAllRelation();
//        } else {
//            String rid = ridText.getText();
//            if (!StringUtil.isBlank(rid)) {
//                friendInfo = getMemberMap(rid, firstSoftHandler);
//            } else {
//                JOptionPane.showMessageDialog(this, "请先选择群", title, JOptionPane.ERROR_MESSAGE);
//                return;
//            }
//        }
//        listFrame.openFriendList(friendInfo, relationInfo, choseRid);
//        String idObj = listFrame.getIdObj();
//        String idType = listFrame.getIdType();
//        if (!StringUtil.isEmpty(idObj)) {
//            if (choseRid) {
//                ridText.setText(idObj);
//            } else {
//                uidText.setText(idObj);
//            }
//            SwingHelper.addLog("CHOSE_SEND_OBJ_SUCCESS", idType, idObj);
//            SystemModel.selectGroupId = idObj;
//        }
//        listFrame.dispose();
//        listFrame = null;
    }

//    private Map<String, UserInfo> getMemberMap(String rid, SoftHandler firstSoftHandler) throws Exception {
//        RelationInfo relationInfo = firstSoftHandler.getRelationInfo(rid);
//        Map<String, UserInfo> memberMap = new HashMap<>(16);
//        if (relationInfo != null) {
//            String memberListStr = firstSoftHandler.queryMemberList(relationInfo.getPt());
//            Map<String, Object> memberRes = JsonUtils.getMap(memberListStr);
//            String status0 = memberRes.getOrDefault("resultCode", "0").toString();
//            if ("1".equals(status0)) {
//                memberRes = (Map<String, Object>) memberRes.get("data");
//                List<Map<String, Object>> memberList = (List<Map<String, Object>>) memberRes.get("members");
//                for (Map<String, Object> member0 : memberList) {
//                    String userEmchatName = member0.get("userId").toString();
//                    String nickname = member0.get("nickname").toString();
//                    UserInfo userInfo = new UserInfo();
//                    userInfo.setUid(userEmchatName);
//                    userInfo.setUnk(nickname);
//                    memberMap.put(nickname, userInfo);
//                }
//            }
//        }
//
//        return memberMap;
//    }

    private SoftHandler getFirstSoftHandler() {
        for (MapBean value : accountMap.values()) {
            String status = value.getString("status");
            if ("在线".equals(status)) {
                String phone = value.getString("phone");
                SoftHandler softHandler = softHandlerMap.get(phone);
                if (softHandler != null) {
                    return softHandler;
                }
            }
        }
        return null;
    }

    @Override
    protected void doInit() {
        //顶部
        JPanel topPanel = new JPanel();
        setCommonColor(topPanel);
        topPanel.setBorder(BorderFactory.createEmptyBorder(7, 10, 2, 10));
        topPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 2));


//        JPanel gridPanel = new JPanel();
//        setCommonColor(gridPanel);
//        gridPanel.setLayout(new BorderLayout());
//
//        JPanel settingPanel = new JPanel();
//        setCommonColor(settingPanel);
//        settingPanel.setBorder(BorderFactory.createEmptyBorder(7, 10, 2, 10));
//        settingPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 2));
//
//        JPanel logPanel = new JPanel();
//        setCommonColor(logPanel);
//        logPanel.setLayout(new BorderLayout());

        //中雷提示框
        JPanel zlPanel = new JPanel();
        setCommonColor(zlPanel);
        zlPanel.setLayout(new BorderLayout());

        //智能发包
        JPanel znfbPanel = new JPanel();
         setCommonColor(znfbPanel);
        znfbPanel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1,Color.gray));
        znfbPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        //发包
        JPanel fbPanel = new JPanel();
        setCommonColor(fbPanel);
        fbPanel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1,Color.gray));
        fbPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));





        //init elements
//        logTextArea = new JTextArea("运行日志：", 8, 30);
//        logTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 13));
//        logTextArea.setEditable(false);
//        logTextArea.setLineWrap(true);
//        logTextArea.setEnabled(true);
//        setCommonColor(logTextArea);
//        logScrollPane = new JScrollPane(logTextArea);
//        Dimension size = logTextArea.getPreferredSize();
//        setCommonColor(logScrollPane.getViewport());
//        logScrollPane.setBounds(0, 0, size.width, size.height);

        //top
        JButton ctjBtn = new JButton("查统计");
        ctjBtn.setActionCommand("ctjBtn");
        ctjBtn.addActionListener(this);
        ctjBtn.setEnabled(true);
        JLabel fblsLabel = new JLabel("发包流水");
         fblsText = new JLabel("");
        JLabel fbbsLabel = new JLabel("发包包数");
         fbbssText = new JLabel("");
        JLabel lqjeLabel = new JLabel("领取金额");
         lqjeText = new JLabel("");
        JLabel ykLabel =  new JLabel("盈亏");
         ykText = new JLabel("");
        topPanel.add(ctjBtn);
        topPanel.add(fblsLabel);
        topPanel.add(fblsText);
        topPanel.add(fbbsLabel);
        topPanel.add(fbbssText);
        topPanel.add(lqjeLabel);
        topPanel.add(lqjeText);
        topPanel.add(ykLabel);
        topPanel.add(ykText);




        //中雷
        Object[][] playerInfo = {};
        // 创建表格中的横标题
        String[] Names = {"中奖情况", "标题", "金额", "中奖尾数","总返"};
         model = new DefaultTableModel(playerInfo,Names);
        zlLogText.setModel(model);
        zlLogText.setPreferredScrollableViewportSize(new Dimension(550, 100));
        // 将表格加入到滚动条组件中
        scrollPane = new JScrollPane(zlLogText);
        setCommonColor(zlLogText);

//        JScrollPane zlScrollPane = new JScrollPane(zlLogText);
//        Dimension zlsize = zlLogText.getPreferredSize();
//        setCommonColor(zlScrollPane.getViewport());
//        zlScrollPane.setBounds(0, 0, zlsize.width, zlsize.height);


        //智能发包
        JLabel jLabel = new JLabel("智能发包:                                                                       ");
        JLabel fbjeLabel = new JLabel("发包金额");
         fbjeText = new JTextField(8);
        JLabel bsLabel  = new JLabel("             包数");
         bsText = new JTextField(8);
        JLabel hbbtLabel = new JLabel("   红包标题");
         hbbtText = new JTextField(10);
        JLabel jgLabel = new JLabel("        间隔");
         jgText =new JTextField(8);
        JLabel zfmmLabel= new JLabel(   "       支付密码");
        JLabel kg = new JLabel("       ");
         zfmmText = new JTextField(8);
         JButton btBtn =  new JButton("设置标题");
         btBtn.setEnabled(true);
         btBtn.setActionCommand("setTitle");
         btBtn.addActionListener(this);
        JButton fbqlBtn = new JButton("选择发包群聊");
        fbqlBtn.setEnabled(true);
        fbqlBtn.setActionCommand("sendGroup");
        fbqlBtn.addActionListener(this);
        znhm = new JCheckBox("智能换码");
         lbjx = new JCheckBox("领包继续                 ");
         f = new JCheckBox("发");
         tz= new JTextField(2);
        JLabel fLabel = new JLabel("包停止");
         cctzfb = new JCheckBox("出错停止发包");
         zltzfb = new JCheckBox("中雷停止发包");

         k = new JCheckBox("空");
        hm= new JTextField(2);
        JLabel kLabel = new JLabel("包换码");
         lqslhb  = new JCheckBox("领取私聊红包,延迟");
        m = new JTextField(2);
        JLabel mlq = new JLabel("秒领取");
        JLabel kg1 = new JLabel("                                  ");
        JLabel bl = new JLabel("倍率");
         blText = new JTextField(4);
        isPf = new JButton("开始");
        isPf.setActionCommand("isPf");
        isPf.addActionListener(this);
        initData();



        JLabel kg2 = new JLabel("                                                                                                 ");
        JButton fybBtn = new JButton("发一包");
        fybBtn.setEnabled(true);
        fybBtn.setActionCommand("sendOne");
        fybBtn.addActionListener(this);
         ksBtn = new JButton("开始");
        ksBtn.setEnabled(true);
        ksBtn.setActionCommand("begin");
        ksBtn.addActionListener(this);
        saveBtn = new JButton("保存配置");
        saveBtn.setEnabled(true);
        saveBtn.setActionCommand("saveConfig");
        saveBtn.addActionListener(this);


//         znfbLogText = new JTextArea("运行日志：", 21, 30);
        znfbLogText.setFont(new Font("微软雅黑", Font.PLAIN, 13));
        znfbLogText.setEditable(false);
        znfbLogText.setLineWrap(true);
        znfbLogText.setEnabled(true);
        znfbLogText.setCaretPosition(znfbLogText.getText().length());
        setCommonColor(znfbLogText);
         znfbLogScrollPane = new JScrollPane(znfbLogText);
        Dimension znfbsize = znfbLogText.getPreferredSize();
        setCommonColor(znfbLogScrollPane.getViewport());
        znfbLogScrollPane.setBounds(0, 0, znfbsize.width, znfbsize.height);

        znfbPanel.add(jLabel);
        znfbPanel.add(fbjeLabel);
        znfbPanel.add(fbjeText);
        znfbPanel.add(bsLabel);
        znfbPanel.add(bsText);
        znfbPanel.add(hbbtLabel);
        znfbPanel.add(hbbtText);
        znfbPanel.add(jgLabel);
        znfbPanel.add(jgText);
        znfbPanel.add(zfmmLabel);
        znfbPanel.add(zfmmText);
        znfbPanel.add(btBtn);
        znfbPanel.add(kg);
        znfbPanel.add(fbqlBtn);
        znfbPanel.add(znhm);
        znfbPanel.add(lbjx);
        znfbPanel.add(f);
        znfbPanel.add(tz);
        znfbPanel.add(fLabel);
        znfbPanel.add(cctzfb);
        znfbPanel.add(zltzfb);
        znfbPanel.add(k);
        znfbPanel.add(hm);
        znfbPanel.add(kLabel);
        znfbPanel.add(lqslhb);
        znfbPanel.add(m);
        znfbPanel.add(mlq);
        znfbPanel.add(kg1);
        znfbPanel.add(bl);
        znfbPanel.add(blText);
        znfbPanel.add(isPf);
        znfbPanel.add(kg2);
        znfbPanel.add(fybBtn);
        znfbPanel.add(ksBtn);
        znfbPanel.add(saveBtn);
        znfbPanel.add(znfbLogScrollPane);



        //发包
        JPanel fbPanel1 = new JPanel();
//        fbPanel1.setBorder(BorderFactory.createEmptyBorder(7, 10, 2, 10));
        fbPanel1.setLayout(new BorderLayout());
        JPanel fbPanel2 = new JPanel();
        setCommonColor(fbPanel2);
        fbPanel2.setLayout(new BorderLayout());





        //发包托
        JLabel fbLabel =  new JLabel("发包托:                                                                                                                                                 ");
        JLabel fbje1 =  new JLabel("发包金额");
         fbjeText1 = new JTextField(5);
        JLabel fbbs1 = new JLabel("发包包数");
          fbbsText1 = new JTextField(5);
        JLabel fbjg1 = new JLabel("发包间隔");
         fbjgText1 = new JTextField(5);

        JButton fbdxBtn1 = new JButton("选择发包对象");
        fbdxBtn1.setActionCommand("xzfbdx");
        fbdxBtn1.addActionListener(this);
        JLabel zdtzbs = new JLabel("自动停止包数");
         zdtzbsText = new JTextField(5);

        JLabel zdtzje  = new JLabel("自动停止金额");
         zdtzjeText = new JTextField(5);
         fbkgBtn = new JButton("开始");
        fbkgBtn.setActionCommand("fbbegin");
        fbkgBtn.addActionListener(this);





        fbPanel.add(fbLabel);
        fbPanel.add(fbje1);
        fbPanel.add(fbjeText1);
        fbPanel.add(fbbs1);
        fbPanel.add(fbbsText1);
        fbPanel.add(fbbsText1);
        fbPanel.add(fbjg1);
        fbPanel.add(fbjgText1);
        fbPanel.add(fbdxBtn1);
        fbPanel.add(zdtzbs);
        fbPanel.add(zdtzbsText);
        fbPanel.add(zdtzje);
        fbPanel.add(zdtzjeText);
//        fbPanel.add(isPf);
        fbPanel.add(fbkgBtn);




        fbLogText.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1,Color.gray));
        fbLogText.setFont(new Font("微软雅黑", Font.PLAIN, 13));
        fbLogText.setEditable(false);
        fbLogText.setLineWrap(true);
        fbLogText.setEnabled(true);
        fbLogText.setCaretPosition(fbLogText.getText().length());
        setCommonColor(fbLogText);
        JScrollPane fbLogScrollPane = new JScrollPane(fbLogText);
//        fbLogScrollPane.setBorder();
        Dimension fbsize = fbLogScrollPane.getPreferredSize();
        setCommonColor(fbLogScrollPane.getViewport());
        fbLogScrollPane.setBounds(0, 0, fbsize.width, fbsize.height);
        fbPanel.add(fbLogText);

















//
//        recordGrid = new JTable(1, 5) {
//            @Override
//            public boolean isCellEditable(int row, int column) {
//                return column == 4;
//            }
//        };
//        addRightMenu(recordGrid);
//        setCommonColor(recordGrid);
//        setCommonColor(recordGrid.getTableHeader());
//        JScrollPane tableScrollPane = new JScrollPane(recordGrid);
//        setCommonColor(tableScrollPane.getViewport());

        // setting element
//        startBtn = new JButton("开始");
//        startBtn.setActionCommand("start");
//        startBtn.addActionListener(this);
//
//        stopBtn = new JButton("暂停");
//        stopBtn.setActionCommand("stop");
//        stopBtn.addActionListener(this);
//        stopBtn.setEnabled(false);
//
//        JButton choseRidBtn = new JButton("选择群");
//        choseRidBtn.setActionCommand("choseRid");
//        choseRidBtn.addActionListener(this);
//        choseRidBtn.setEnabled(true);
//
//        JButton choseUidBtn = new JButton("选择好友");
//        choseUidBtn.setActionCommand("choseUid");
//        choseUidBtn.addActionListener(this);
//        choseUidBtn.setEnabled(true);
//
//        JButton saveBtn = new JButton("保存配置");
//        saveBtn.setActionCommand("save");
//        saveBtn.addActionListener(this);
//        saveBtn.setEnabled(true);
//
//        JButton loadBtn = new JButton("加载账户");
//        loadBtn.setActionCommand("load");
//        loadBtn.addActionListener(this);
//        loadBtn.setEnabled(true);
//
//        JButton loginBtn = new JButton("批量登录");
//        loginBtn.setActionCommand("login");
//        loginBtn.addActionListener(this);
//        loginBtn.setEnabled(true);
//        JButton logoutBtn = new JButton("批量退出");
//        logoutBtn.setActionCommand("logout");
//        logoutBtn.addActionListener(this);
//        logoutBtn.setEnabled(true);
//
//        JLabel ridLabel = new JLabel("指定群: ");
//        JLabel takeSleepLabel = new JLabel("延迟时间: ");
//        JLabel uidLabel = new JLabel("指定人: ");
//
//        ridText = new JTextField(12);
//        uidText = new JTextField(12);
//        ridCbx = new JCheckBox("是否抢所有群");
//        ridCbx.setBackground(commonBgColor);
//        uidCbx = new JCheckBox("是否抢所有人");
//        uidCbx.setBackground(commonBgColor);
//
//        takeSleepText = new JTextField(12);
//
//        firstSomeCbx = new JCheckBox("当第");
//        firstSomeCbx.setBackground(commonBgColor);
//        lastSomeCbx = new JCheckBox("抢剩余的");
//        lastSomeCbx.setBackground(commonBgColor);
//        firstSomeText = new JTextField(3);
//        lastSomeText = new JTextField(3);

//        //add elements
//        gridPanel.add(tableScrollPane);

//        settingPanel.add(ridLabel);
//        settingPanel.add(ridText);
//        settingPanel.add(ridCbx);
//        settingPanel.add(choseRidBtn);
//        settingPanel.add(new JLabel("       "));
//        settingPanel.add(uidLabel);
//        settingPanel.add(uidText);
//        settingPanel.add(uidCbx);
//        settingPanel.add(choseUidBtn);
//        settingPanel.add(takeSleepLabel);
//        settingPanel.add(takeSleepText);
//        settingPanel.add(new JLabel("毫秒                                        "));
//
//        settingPanel.add(firstSomeCbx);
//        settingPanel.add(firstSomeText);
//        settingPanel.add(new JLabel("包被领完之后开抢                                            "));
//        settingPanel.add(lastSomeCbx);
//        settingPanel.add(lastSomeText);
//        settingPanel.add(new JLabel("包                                                             "));
//
//        settingPanel.add(loginBtn);
//        settingPanel.add(logoutBtn);
//        settingPanel.add(saveBtn);
//        settingPanel.add(new JLabel("                                                      "));
//        settingPanel.add(startBtn);
//        settingPanel.add(stopBtn);
//
//        logPanel.add(logScrollPane);

        //events
        DropTargetListener listener = new DropTargetListener() {
            @Override
            public void dragEnter(DropTargetDragEvent dtde) {
            }

            @Override
            public void dragOver(DropTargetDragEvent dtde) {

            }

            @Override
            public void dropActionChanged(DropTargetDragEvent dtde) {

            }

            @Override
            public void dragExit(DropTargetEvent dte) {

            }

            @Override
            public void drop(DropTargetDropEvent dtde) {
                System.out.println("drop");
                boolean isAccept = false;
                if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                    dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                    try {
                        String text = dtde.getTransferable().getTransferData(DataFlavor.stringFlavor).toString();
                        System.out.println("drop text: " + text);
                        renderByDrop(text);
                        isAccept = true;
                    } catch (UnsupportedFlavorException | IOException e) {
                        e.printStackTrace();
                    }
                }
                if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                    dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                    try {
                        List<File> list = (List<File>) (dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor));
                        StringBuilder sbf = new StringBuilder();
                        for (File file : list) {
                            String str = FileUtil.readFileAsString(file.getAbsolutePath());
                            if (str != null) {
                                sbf.append(str);
                            }
                        }
                        System.out.println("drop text: " + sbf);
                        renderByDrop(sbf.toString());
                        isAccept = true;
                    } catch (UnsupportedFlavorException | IOException e) {
                        e.printStackTrace();
                    }
                }

                if (isAccept) {
                    dtde.dropComplete(true);
                }
            }
        };
//        DropTarget dropTarget = new DropTarget(gridPanel, DnDConstants.ACTION_COPY_OR_MOVE, listener, true);




        zlPanel.add(scrollPane);
        //set layouts
        Container container = getContentPane();
        container.setBackground(commonBgColor);
        setLayout(null);

        int leftWidth = 600;
        int rightWidth = 300;
        int gridHeight = 350;
        int settingHeight = 250;
        int topHeight = gridHeight + settingHeight;
        topPanel.setBounds(0,0,1190,50);
        zlPanel.setBounds(40, 50, leftWidth, gridHeight);
        znfbPanel.setBounds(leftWidth+40+30,50,400,750);
        fbPanel.setBounds(40,gridHeight+70,leftWidth,380);
//        zlPanel.setBounds();

        container.add(topPanel);
        container.add(zlPanel);
        container.add(znfbPanel);
        container.add(fbPanel);
//        container.add(settingPanel);
//        container.add(logPanel);
//        container.add(zlPanel);
    }


    public static List<Map<String,Object>> getList(String tableName){

        List<Map<String,Object>> list =null;
        try {
            if(tableName.equals("config")){
                sqliteHelper.executeQuery("select * from " + tableName + " where userid=" + userInfo.getUid(), new ResultSetExtractor<List<String>>() {
                    @Override
                    public List<Map<String, Object>> extractData(ResultSet rs) {
                        try {
                            if (!rs.next()) {
                                sqliteHelper.executeUpdate("insert into config values('"+userInfo.getUid()+"',null,0,null,0,null,0,0,0,null,0,0,0,null,0,null,null)");
                            }
                        } catch (SQLException | ClassNotFoundException throwables) {
                            throwables.printStackTrace();
                        }
                        return null;
                    }
                });
                list = sqliteHelper.executeQuery("select * from "+tableName+" where userid=" + userInfo.getUid(), new ResultSetExtractor<List<String>>() {
                    @Override
                    public List<Map<String, Object>> extractData(ResultSet rs) {
                        try {
                            List<Map<String,Object>> list = new ArrayList<>();
                            Map<String,Object> map = new HashMap<>();
                            map.put("userid",rs.getString("userid"));
                            map.put("money",rs.getString("money"));
                            map.put("page_num",rs.getString("page_num"));
                            map.put("title",rs.getString("title"));
                            map.put("jg",rs.getString("jg"));
                            map.put("sendId",rs.getString("sendId"));
                            map.put("znhm",rs.getString("znhm"));
                            map.put("lbjx",rs.getString("lbjx"));
                            map.put("f",rs.getString("f"));
                            map.put("f_text",rs.getString("f_text"));
                            map.put("zltzfb",rs.getString("zltzfb"));
                            map.put("cctzfb",rs.getString("cctzfb"));
                            map.put("k",rs.getString("k"));
                            map.put("k_text",rs.getString("k_text"));
                            map.put("lqslhb",rs.getString("lqslhb"));
                            map.put("lqshlb_text",rs.getString("lqshlb_text"));
                            map.put("bl",rs.getString("bl"));
                            System.out.println(map.toString());
                            list.add(map);
                            return list;
                        } catch (SQLException throwables) {
                            throwables.printStackTrace();
                        }
                        return null;
                    }
                });
            }else if(tableName.equals("userdata")){
                 sqliteHelper.executeQuery("select * from "+tableName+" where userid=" + userInfo.getUid(), new ResultSetExtractor<List<String>>() {
                    @Override
                    public List<Map<String, Object>> extractData(ResultSet rs) {
                        try {
                            if(!rs.next()){
                                sqliteHelper.executeUpdate("insert into userdata values(0,0,0,0,"+ SettingFrame.userInfo.getUid()+")");
                            }
                        } catch (SQLException | ClassNotFoundException throwables) {
                            throwables.printStackTrace();
                        }
                        return null;
                    }
                });
                list = sqliteHelper.executeQuery("select * from "+tableName+" where userid=" + userInfo.getUid(), new ResultSetExtractor<List<String>>() {
                    @Override
                    public List<Map<String, Object>> extractData(ResultSet rs) {
                        try {
                            List<Map<String,Object>> list = new ArrayList<>();
                            Map<String,Object> map = new HashMap<>();
                            map.put("fbls",rs.getString("fbls"));
                            map.put("send_page_num",rs.getString("send_page_num"));
                            map.put("lq_money",rs.getString("lq_money"));
                            map.put("yk",rs.getString("yk"));
                            System.out.println(map.toString());
                            list.add(map);
                            return list;
                        } catch (SQLException throwables) {
                            throwables.printStackTrace();
                        }
                        return null;
                    }
                });
            }else if(tableName.equals("title")) {
                sqliteHelper.executeQuery("select * from " + tableName + " where userid=" + userInfo.getUid(), new ResultSetExtractor<List<String>>() {
                    @Override
                    public List<Map<String, Object>> extractData(ResultSet rs) {
                        try {
                            if (!rs.next()) {
                                sqliteHelper.executeUpdate("insert into title values(0," + SettingFrame.userInfo.getUid() + ")");
                            }
                        } catch (SQLException | ClassNotFoundException throwables) {
                            throwables.printStackTrace();
                        }
                        return null;
                    }
                });
                list = sqliteHelper.executeQuery("select * from " + tableName + " where userid=" + userInfo.getUid(), new ResultSetExtractor<List<String>>() {
                    @Override
                    public List<Map<String, Object>> extractData(ResultSet rs) {
                        try {
                            List<Map<String, Object>> list = new ArrayList<>();
                            while (rs.next()) {
                                Map<String, Object> map = new HashMap<>();
                                map.put("name", rs.getString("name"));
                                list.add(map);
                            }
                            return list;
                        } catch (SQLException throwables) {
                            throwables.printStackTrace();
                        }
                        return null;
                    }
                });
                return list;
            }else if(tableName.equals("reddata")){
                sqliteHelper.executeQuery("select * from " + tableName + " where userid=" + userInfo.getUid(), new ResultSetExtractor<List<String>>() {
                    @Override
                    public List<Map<String, Object>> extractData(ResultSet rs) {
                        try {
                            if (!rs.next()) {
                                sqliteHelper.executeUpdate("insert into reddata values(0,0,0,0,0,0,0," + SettingFrame.userInfo.getUid() + ",0)");
                            }
                        } catch (SQLException | ClassNotFoundException throwables) {
                            throwables.printStackTrace();
                        }
                        return null;
                    }
                });


                list = sqliteHelper.executeQuery("select * from " + tableName + " where userid=" + userInfo.getUid(), new ResultSetExtractor<List<String>>() {
                    @Override
                    public List<Map<String, Object>> extractData(ResultSet rs) {
                        try {
                            List<Map<String, Object>> list = new ArrayList<>();
                            while (rs.next()) {
                                Map<String, Object> map = new HashMap<>();
                                map.put("phone", rs.getString("phone"));
                                map.put("name", rs.getString("name"));
                                map.put("groupname", rs.getString("groupname"));
                                map.put("groupno", rs.getString("groupno"));
                                map.put("sendnum", rs.getString("sendnum"));
                                map.put("sendmoney", rs.getString("sendmoney"));
                                map.put("yk", rs.getString("yk"));
                                list.add(map);
                            }
                            return list;
                        } catch (SQLException throwables) {
                            throwables.printStackTrace();
                        }
                        return null;
                    }
                });
                return list;
            }
            return list;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    private void initData() {

        List<Map<String, Object>> list=  this.getList("config");
        Map<String,Object> map=  list.get(0);
        System.out.println();
        fbjeText.setText(Objects.isNull(map.get("money")) ? "": map.get("money").toString()  );
        bsText.setText(Objects.isNull( map.get("page_num")) ? "":  map.get("page_num").toString() );
        hbbtText.setText(Objects.isNull( map.get("title")) ? "": map.get("title").toString());
        jgText.setText(Objects.isNull( map.get("jg")) ? "": map.get("jg").toString() );
        znhm.setSelected(map.get("znhm").toString().equals("1"));
        lbjx.setSelected(map.get("lbjx").toString().equals("1"));
        f.setSelected(map.get("f").toString().equals("1"));
        tz.setText(Objects.isNull(map.get("f_text")) ? "": map.get("f_text").toString());
        cctzfb.setSelected(map.get("cctzfb").toString().equals("1"));
        zltzfb.setSelected(map.get("zltzfb").toString().equals("1"));
        k.setSelected(map.get("k").toString().equals("1"));
        hm.setText(Objects.isNull(map.get("k_text")) ? "": map.get("k_text").toString());
        lqslhb.setSelected(map.get("lqslhb").toString().equals("1"));
        m.setText(Objects.isNull(map.get("lqshlb_text")) ? "": map.get("lqshlb_text").toString());
        blText.setText(Objects.isNull(map.get("bl")) ? "": map.get("bl").toString());


        //判断是否有此用户数据,没有则新建数据
        List<Map<String,Object>> userDataList = this.getList("userdata");
        Map<String,Object> map1 = userDataList.get(0);
        fblsText.setText(Objects.isNull(map1.get("fbls")) ? "":map1.get("fbls").toString());
        fbbssText.setText(Objects.isNull(map1.get("send_page_num")) ? "":map1.get("send_page_num").toString());
        lqjeText.setText(Objects.isNull(map1.get("lq_money")) ? "":map1.get("lq_money").toString());
        ykText.setText(Objects.isNull(map1.get("yk")) ? "":map1.get("yk").toString());




    }

    private void addRightMenu(JTable recordGrid) {
        JPopupMenu popupMenu = new JPopupMenu();

        JMenuItem delMenItem = new JMenuItem();
        delMenItem.setText("设为探测号");
        delMenItem.setActionCommand("setProbeId");
        delMenItem.addActionListener(this);
        popupMenu.add(delMenItem);

        recordGrid.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                //判断是否为鼠标的BUTTON3按钮，BUTTON3为鼠标右键
                if (evt.getButton() == MouseEvent.BUTTON3) {
                    //通过点击位置找到点击为表格中的行
                    int focusedRowIndex = recordGrid.rowAtPoint(evt.getPoint());
                    if (focusedRowIndex == -1) {
                        return;
                    }
                    //将表格所选项设为当前右键点击的行
                    recordGrid.setRowSelectionInterval(focusedRowIndex, focusedRowIndex);
                    //弹出菜单
                    popupMenu.show(recordGrid, evt.getX(), evt.getY());
                }
            }
        });
    }

    private void setCommonColor(JComponent component) {
        component.setBackground(commonBgColor);
    }

    @Override
    protected void afterInit() {
        ThreadUtil.commonScheduleByDelay(() -> {
            for (String phone : accountMap.keySet()) {
                SoftHandler lapu = softHandlerMap.get(phone);
                if (lapu == null) {
                    return;
                }
                MapBean accountInfo = accountMap.get(phone);
                if (accountInfo != null) {
                    if (accountInfo.get("status").toString().contains("离线")) {
                        continue;
                    }
                    try {
                        Integer balance = lapu.queryBalance();
                        accountInfo.put("bal", MathUtil.getYuanFromFen(balance) + "");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            renderTableByAccount();
        }, 30, 3, TimeUnit.SECONDS);
    }

    private synchronized void renderTable(List<MapBean> beanList) {
        if (beanList == null || beanList.isEmpty()) {
            return;
        }
        List<MapBean> sortList = beanList.stream().sorted((o1, o2) -> {
            String seq = o1.getString("bal");
            String seq2 = o2.getString("bal");
            if (StringUtil.isBlank(seq) || StringUtil.isBlank(seq2)) {
                return 0;
            }
            float a = Float.parseFloat(seq);
            float b = Float.parseFloat(seq2);
            return (int) (b - a);
        }).collect(Collectors.toList());

        Object probeId = ClientConfigHelper.getConfig().get("probeId");

        DefaultTableModel sendGridModel = (DefaultTableModel) recordGrid.getModel();
        sendGridModel.setDataVector(new Object[][]{}, new Object[]{"用户昵称", "手机", "余额", "状况", "操作"});
        SystemModel.loginList = sortList;
        SystemModel.loginCount = sortList.size();

        for (MapBean mapBean : sortList) {
            String status0 = "";
            if (mapBean.getString("phone").equals(probeId)) {
                status0 = "(探测号)";
            }
            sendGridModel.addRow(new Object[]{
                    mapBean.get("nick"),
                    mapBean.get("phone"),
                    mapBean.getString("bal"),
                    mapBean.getString("status") + status0,
                    mapBean,
            });
        }

        recordGrid.setRowHeight(25);
        recordGrid.setModel(sendGridModel);
        if (recordGrid.getRowCount() > 0) {
            recordGrid.setRowSelectionInterval(0, 0);
        }
        OperationCellEditor cellEditor = new OperationCellEditor(this, commonBgColor);
        setColumnEditor(4, cellEditor);
        setColumnRender(4, cellEditor);
//        setColumnWidth(0, 50);
    }

    private void setColumnRender(int index, TableCellRenderer cellRender) {
        TableColumnModel columnModel = recordGrid.getColumnModel();
        TableColumn column = columnModel.getColumn(index);
        column.setCellRenderer(cellRender);
    }

    private void setColumnEditor(int index, TableCellEditor cellEditor) {
        TableColumnModel columnModel = recordGrid.getColumnModel();
        TableColumn column = columnModel.getColumn(index);
        column.setCellEditor(cellEditor);
    }

    private void setColumnWidth(int index, int pwid) {
        setColumnWidth(index, pwid, pwid, pwid);
    }

    private void setColumnWidth(int index, int pwid, int max, int min) {
        TableColumnModel columnModel = recordGrid.getColumnModel();
        TableColumn column = columnModel.getColumn(index);
        column.setPreferredWidth(pwid);
        column.setMaxWidth(max);
        column.setMinWidth(min);
    }

    public void save(){
        String fbje= StringUtil.isBlank(fbjeText.getText()) ? null :fbjeText.getText()   ;
        String bs=StringUtil.isBlank(bsText.getText()) ? null :bsText.getText() ;
        String title= StringUtil.isBlank(hbbtText.getText()) ? null : hbbtText.getText() ;
        String jg = StringUtil.isBlank(jgText.getText()) ? null : jgText.getText() ;
        String sendId= fbId;
        Integer isHm = znhm.isSelected() ? 1 : 0;
        Integer jx =  lbjx.isSelected()? 1: 0;
        Integer fa = f.isSelected()? 1: 0;
        String f_text = StringUtil.isBlank(tz.getText()) ? null : tz.getText()  ;
        Integer cctz = cctzfb.isSelected() ? 1 : 0;
        Integer zltz = zltzfb.isSelected() ? 1: 0;
        Integer kong = k.isSelected()? 1: 0;
        String kongText = StringUtil.isBlank(hm.getText()) ? null : hm.getText();
        Integer lqsl = lqslhb.isSelected() ? 1: 0;
        String miao =StringUtil.isBlank(m.getText()) ? null : m.getText() ;
        String beilv = StringUtil.isBlank(blText.getText()) ? null : blText.getText();
        List<Map<String,Object>>  list = this.getList("config");
        String sql ="";
       if(list.get(0)==null){
            sql = " insert into config values('"+userInfo.getUid()+"','"+fbje+"','"+bs+"','"+title+"','"+jg+"','"+sendId+"','"
                   +isHm+"','"
                   +jx+"','"
                   +fa+"','"
                   +f_text+"','"
                   +zltz+"','"
                   +cctz+"','"
                   +kong+"','"
                   +kongText+"','"
                   +lqsl+"','"
                   +miao+"','"
                   +beilv
                   +"')";
       }else{
           sql=  "update config set money = "+fbje+",page_num="+bs+",title="+title+",jg="+jg+",sendId="+sendId+",znhm="+isHm+
                   ",lbjx="+jx+
                   ",f="+fa+
                   ",f_text="+f_text+
                   ",zltzfb="+zltz+
                   ",cctzfb="+cctz+
                   ",k="+kong+
                   ",k_text="+kongText+
                   ",lqslhb="+lqsl+
                   ",lqshlb_text="+miao+
                   ",bl="+beilv+
                   " where userid="+userInfo.getUid()
           ;
       }
        System.out.println( sql);
        try {
            sqliteHelper.executeUpdate(sql);
            znfbLogText.append("\r\n保存设置成功!");
            SettingFrame.znfbLogText.setCaretPosition(SettingFrame.znfbLogText.getText().length());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }



    @Override
    public void saveConfig() {
//        MapBean config = new MapBean();
//        config.put("takeSleep", takeSleepText.getText());
//        config.put("rid", ridText.getText());
//        config.put("uid", uidText.getText());
//        config.put("ridOn", ridCbx.isSelected());
//        config.put("uidOn", uidCbx.isSelected());
//        config.put("firstSomeOn", firstSomeCbx.isSelected());
//        config.put("lastSomeOn", lastSomeCbx.isSelected());
//        config.put("firstSomeCount", firstSomeText.getText());
//        config.put("lastSomeCount", lastSomeText.getText());
//
//        config.put("__work", work);
//
//        ClientConfigHelper.saveConfig(config);
    }



    @Override
    public void renderConfig() {
//        MapBean config = ClientConfigHelper.getConfig();
//        takeSleepText.setText(config.getOrDefault("takeSleep", "2000").toString());
//        ridText.setText(config.getString("rid"));
//        uidText.setText(config.getString("uid"));
//        firstSomeText.setText(config.getString("firstSomeCount"));
//        lastSomeText.setText(config.getString("lastSomeCount"));
//        ridCbx.setSelected(config.getBoolean("ridOn"));
//        uidCbx.setSelected(config.getBoolean("uidOn"));
//        Boolean firstSomeOn = config.getBoolean("firstSomeOn");
//        firstSomeCbx.setSelected(firstSomeOn == null ? false : firstSomeOn);
//        Boolean lastSomeOn = config.getBoolean("lastSomeOn");
//        lastSomeCbx.setSelected(lastSomeOn == null ? false : lastSomeOn);
//
//        config.put("__work", work);
//        ClientConfigHelper.saveConfig(config);
    }

    @Override
    protected void renderBalance(Integer balanceFen) {
        //delete
    }

    @Override
    public void setTotal(Integer totalSend, Integer totalTake) {
        // delete
    }

    @Override
    protected void setAvatarByUserInfo() throws Exception {
        //nothings to do
    }

    @Override
    protected void clearLog() {
        logTextArea.setText("");
    }

    @Override
    protected void addListenerToLog(KeyListener keyListener) {
//        logTextArea.addKeyListener(keyListener);
//        logTextArea.requestFocus();
    }

    @Override
    protected void testLoginInfoOverdue() {
        //delete
    }

    @Override
    protected void testReconnectWss() {

    }

    @Override
    protected String getSettingLog() {
        return logTextArea.getText();
    }

    @Override
    protected String getSettingSwingTitle(String version, String title, int day, int hour, int minute, int second) {
        return super.getSettingSwingTitle(version, title, day, hour, minute, second);
    }

    @Override
    protected int getSettingHeight() {
        return 850;
    }

    @Override
    protected int getSettingWith() {
        return 1100;
    }


    public static void renderTable(){
        for (Map<String, Object> map : tableDate) {
            Object[] data = new Object[]{map.get("isZJ"),map.get("title"),map.get("pagenum"),map.get("ws"),map.get("zf")};
            if(!Boolean.parseBoolean(map.get("isRender").toString())){
                model.addRow(data);
            }

            map.put("isRender",true);
        }
        zlLogText.setModel(model);
        JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
        System.out.println(scrollBar.getMaximum());
        scrollBar.setValue(scrollBar.getMaximum()+100);

    }



}
